<template>
  <div class="upload">
    <el-upload
      action="/api/upload"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :limit="limit"
      :class="{ disabled: isMax }"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-upload"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: {
    limit: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      isMax: false,
      imgList: [],
    };
  },
  methods: {
    beforeUpload(file) {
      //判断图片大小 与类型
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isPG = isJPG || isPNG;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isPG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isPG && isLt2M;
    },
    handleRemove(file) {
      var del_img = file.response.data;
      // 从imgList 找到对应的下标索引
      const index = this.imgList.findIndex((item) => item === del_img);
      this.imgList.splice(index, 1)
      if (this.imgList.length < 3) {
        this.isMax = false;
      }
      this.$emit("changeImg", this.imgList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(file) {
      console.log(file);
      this.imgList.push(file.data);
      if (this.imgList.length >= this.limit) {
        this.isMax = true;
      }
      this.$emit("changeImg", this.imgList);
    },
  },
};
</script>

<style lang="less" scoped>
.disabled /deep/.el-upload--picture-card {
  display: none !important;
}
</style>